package com.java110.mall.shop.cmd.shop;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.cache.Java110RedisConfig;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.account.AccountDto;
import com.java110.dto.distributionMode.DistributionModeDto;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.store.StoreDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.acct.IAccountBondObjInnerServiceSMO;
import com.java110.intf.acct.IAccountInnerServiceSMO;
import com.java110.intf.goods.IDistributionModeInnerServiceSMO;
import com.java110.intf.shop.IShopInnerServiceSMO;
import com.java110.intf.user.*;
import com.java110.po.account.AccountPo;
import com.java110.po.distributionMode.DistributionModePo;
import com.java110.po.org.OrgPo;
import com.java110.po.org.OrgStaffRelPo;
import com.java110.po.privilege.PrivilegeUserPo;
import com.java110.po.shop.ShopPo;
import com.java110.po.store.StorePo;
import com.java110.po.user.StoreStaffPo;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.constant.StoreUserRelConstant;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * pc 端完善 商户和店铺信息
 */
@Java110Cmd(serviceCode = "shop.pcReplenishStoreAndShop")
public class PcReplenishStoreAndShopCmd extends Cmd {

    public static final String CODE_PREFIX_ID = "10";

    @Autowired
    private IStoreV1InnerServiceSMO storeV1InnerServiceSMOImpl;

    @Autowired
    private IStoreAttrV1InnerServiceSMO storeAttrV1InnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;

    @Autowired
    private IStoreStaffV1InnerServiceSMO storeUserV1InnerServiceSMOImpl;

    @Autowired
    private IOrgV1InnerServiceSMO orgV1InnerServiceSMOImpl;

    @Autowired
    private IOrgStaffRelV1InnerServiceSMO orgStaffRelV1InnerServiceSMOImpl;

    @Autowired
    private IPrivilegeUserV1InnerServiceSMO privilegeUserV1InnerServiceSMOImpl;

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IAccountInnerServiceSMO accountInnerServiceSMOImpl;

    @Autowired
    private IAccountBondObjInnerServiceSMO accountBondObjInnerServiceSMOImpl;


    @Autowired
    private IDistributionModeInnerServiceSMO distributionModeInnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "address", "未包含店铺地址");
        Assert.hasKeyAndValue(reqJson, "areaAddress", "未包含区域地址");
        Assert.hasKeyAndValue(reqJson, "areaCode", "未包含区域");
        Assert.hasKeyAndValue(reqJson, "name", "未包含公司名称");
        Assert.hasKeyAndValue(reqJson, "nearbyLandmarks", "未包含附近");
        Assert.hasKeyAndValue(reqJson, "shopName", "未包含店铺名称");
        Assert.hasKeyAndValue(reqJson, "shopType", "未包含店铺类型");
        Assert.hasKeyAndValue(reqJson, "storeTypeCd", "未包含商户类型");
        Assert.hasKeyAndValue(reqJson, "tel", "未包含联系电话");
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        String userId = cmdDataFlowContext.getReqHeaders().get("user-id");

        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        List<UserDto> userDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "用户不存在");
        reqJson.put("userName", userDtos.get(0).getName());

        StorePo storePo = BeanConvertUtil.covertBean(reqJson, StorePo.class);
        storePo.setStoreId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        storePo.setStoreTypeCd(reqJson.getString("storeTypeCd"));
        storePo.setState(StoreDto.STATE_NORMAL);
        storePo.setName(reqJson.getString("name"));
        //storePo.setUserId("-1");
        storePo.setAddress(reqJson.getString("address"));
        storePo.setTel(reqJson.getString("tel"));
//         storePo.setNearbyLandmarks(reqJson.getString("nearbyLandmarks"));
//        if (!reqJson.containsKey("mapY")) {
//            storePo.setMapY("1");
//        }
//        if (!reqJson.containsKey("mapX")) {
//            storePo.setMapX("1");
//        }
        int flag = storeV1InnerServiceSMOImpl.saveStore(storePo);

        if (flag < 1) {
            throw new CmdException("保存数据失败");
        }

        //保存 商户和用户的关系
        StoreStaffPo storeUserPo = new StoreStaffPo();
        storeUserPo.setStoreStaffId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        storeUserPo.setAdminFlag(StoreUserRelConstant.REL_ADMIN);
        storeUserPo.setStoreId(storePo.getStoreId());
        storeUserPo.setStaffId(userDtos.get(0).getUserId());
        storeUserPo.setStaffName(userDtos.get(0).getName());
        storeUserPo.setTel(userDtos.get(0).getTel());
        flag = storeUserV1InnerServiceSMOImpl.saveStoreStaff(storeUserPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }

        //保存公司级组织
        OrgPo orgPo = new OrgPo();
        orgPo.setOrgName(storePo.getName());
        orgPo.setOrgLevel("1");
        orgPo.setOrgId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_orgId));
        orgPo.setAllowOperation("F");
        orgPo.setBelongCommunityId("9999");
        orgPo.setParentOrgId(orgPo.getOrgId());
        orgPo.setStoreId(storePo.getStoreId());

        flag = orgV1InnerServiceSMOImpl.saveOrg(orgPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }

        //添加组织 员工关系
        OrgStaffRelPo orgStaffRelPo = new OrgStaffRelPo();
        orgStaffRelPo.setOrgId(orgPo.getOrgId());
        orgStaffRelPo.setStaffId(userId);
        orgStaffRelPo.setRelId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        orgStaffRelPo.setRelCd(StoreUserRelConstant.REL_ADMIN);
        orgStaffRelPo.setStoreId(storePo.getStoreId());
        flag = orgStaffRelV1InnerServiceSMOImpl.saveOrgStaffRel(orgStaffRelPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }


        String defaultPrivilege = MappingCache.getValue(MappingConstant.DOMAIN_DEFAULT_PRIVILEGE_ADMIN, StoreDto.STORE_TYPE_MALL);

        Assert.hasLength(defaultPrivilege, "未配置商城默认权限");
        PrivilegeUserPo privilegeUserPo = new PrivilegeUserPo();
        privilegeUserPo.setPrivilegeFlag("1");
        privilegeUserPo.setStoreId(storePo.getStoreId());
        privilegeUserPo.setUserId(userId);
        privilegeUserPo.setpId(defaultPrivilege);
        privilegeUserPo.setPuId(GenerateCodeFactory.getGeneratorId("10"));

        flag = privilegeUserV1InnerServiceSMOImpl.savePrivilegeUser(privilegeUserPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }

        //保存商铺
        saveShop(storePo, reqJson);

        //开户
        addAccountDto(storePo, reqJson);

        String storeInfo = CommonCache.getValue("getStoreInfo" + Java110RedisConfig.GET_STORE_INFO_EXPIRE_TIME_KEY + "::" + userId);
        if (!StringUtil.isEmpty(storeInfo)) {
            CommonCache.removeValue("getStoreInfo" + Java110RedisConfig.GET_STORE_INFO_EXPIRE_TIME_KEY + "::" + userId);
        }
    }


    /**
     * 开户
     *
     * @param storePo
     * @param reqJson
     */
    private void addAccountDto(StorePo storePo, JSONObject reqJson) {

        AccountPo accountPo = new AccountPo();
        accountPo.setAmount("0");
        accountPo.setAcctId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_acctId));
        accountPo.setObjId(storePo.getStoreId());
        accountPo.setObjType(AccountDto.OBJ_TYPE_STORE);
        accountPo.setAcctType(AccountDto.ACCT_TYPE_CASH);
        accountPo.setAcctName(storePo.getName());
        accountPo.setPartId(reqJson.getString("shopId"));
        accountInnerServiceSMOImpl.saveAccount(accountPo);

    }


    /**
     * Assert.hasKeyAndValue(reqJson, "address", "未包含店铺地址");
     * Assert.hasKeyAndValue(reqJson, "areaAddress", "未包含区域地址");
     * Assert.hasKeyAndValue(reqJson, "areaCode", "未包含区域");
     * Assert.hasKeyAndValue(reqJson, "name", "未包含公司名称");
     * Assert.hasKeyAndValue(reqJson, "nearbyLandmarks", "未包含附近");
     * Assert.hasKeyAndValue(reqJson, "shopName", "未包含店铺名称");
     * Assert.hasKeyAndValue(reqJson, "shopType", "未包含店铺类型");
     * Assert.hasKeyAndValue(reqJson, "storeTypeCd", "未包含商户类型");
     * Assert.hasKeyAndValue(reqJson, "tel", "未包含联系电话");
     *
     * @param storePo
     * @param reqJson
     */
    private void saveShop(StorePo storePo, JSONObject reqJson) {

        ShopPo shopPo = new ShopPo();
        shopPo.setShopName(reqJson.getString("shopName"));
        shopPo.setShopDesc("店铺比较懒未完善店铺信息");
        shopPo.setReturnPerson(reqJson.getString("userName"));
        shopPo.setReturnLink(reqJson.getString("tel"));
        shopPo.setStoreId(storePo.getStoreId());
        shopPo.setSendAddress(reqJson.getString("areaAddress") + reqJson.getString("address"));
        shopPo.setReturnAddress(reqJson.getString("areaAddress") + reqJson.getString("address"));
        shopPo.setShopType(reqJson.getString("shopType"));
        shopPo.setOpenType(ShopDto.OPEN_TYPE_SHOP);
        shopPo.setShopRange("无");
        shopPo.setAreaCode(reqJson.getString("areaCode"));
        shopPo.setShopId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_shopId));
        shopPo.setShopLogo("");
        shopPo.setMapX("1");
        shopPo.setMapY("1");

        shopPo.setState(ShopDto.STATE_Y);
        //shopPo.setState(ShopDto.STATE_B);

        int flag = shopInnerServiceSMOImpl.saveShop(shopPo);
        if (flag < 1) {
            throw new CmdException("保存商铺失败");
        }

        //默认保存保证金应收信息
        //saveAccountBond(accoutBond, shopPo);

        //添加派送方式
        DistributionModePo distributionModePo = new DistributionModePo();
        distributionModePo.setFixedFee("0");
        distributionModePo.setbId("-1");
        distributionModePo.setMaximumDistribution("-1");
        //处理商品与配送方式关系
        distributionModePo.setModeId(GenerateCodeFactory.getGeneratorId("16"));
        distributionModePo.setShopId(shopPo.getShopId());
        distributionModePo.setModeName("到店自提");
        distributionModePo.setModeType(DistributionModeDto.MODE_TYPE_USER);
        distributionModePo.setStartDeliveryIn("-1");
        distributionModePo.setStartDeliveryOut("-1");
        flag = distributionModeInnerServiceSMOImpl.saveDistributionMode(distributionModePo);
        if (flag < 1) {
            throw new CmdException("保存店铺配送方式失败");
        }

        reqJson.put("shopId", shopPo.getShopId());

    }
}
